<?php

class Application_Model_RealEstateMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_RealEstate');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_RealEstate $realestate)
	{
		
		$objectMapper = new Application_Model_ObjectMapper();
		$row = $objectMapper->save($realestate);
		$realestate->setObjectId($row);
		$data = array(
				'id_object' => $realestate->getObjectId(),
				'surface' => $realestate->getSurface(),
		);
		
		if (null === ($id = $realestate->getRealestateId())) {
			unset($data['id_realEstate']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_realEstate = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_RealEstate $realestate)
	{
		$addressMapper = new Application_Model_AddressMapper();
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$realestate->setRealestateId($row->id_realEstate);
		$realestate->setObjectId($row->id_object);
		$realestate->setSurface($row->surface);
		
		$objectMapper = new Application_Model_ObjectMapper();
		$realestate = $objectMapper->find($realestate->getObjectId(), $realestate);
	
	
		return $realestate;
	}
	
	public function delete($id)
	{
	
		$realestate = new Application_Model_RealEstate();
		$objectMapper = new Application_Model_ObjectMapper();
		$realestate = $this->find($id, new Application_Model_RealEstate());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_realEstate = ?' => $id));
		}
	
		$objectMapper->delete($realestate->getObjectId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_RealEstate $realestate)
	{
		$objectMapper = new Application_Model_ObjectMapper();
		$requestBuilder = new Application_Model_Builder_Request();
		$doc->addField(Zend_Search_Lucene_Field::Text('surface', $requestBuilder->adjustnumber(4, $realestate->getSurface(), '0'), 'utf-8'));
		$doc = $objectMapper->indexBuilder($doc, $realestate);
	
		return $doc;
	}
}